package org.openmore.platform.controller;

import io.swagger.annotations.*;
import me.chanjar.weixin.common.error.WxErrorException;
import org.openmore.common.exception.OpenmoreException;
import org.openmore.platform.annotation.TokenAuthCheck;
import org.openmore.platform.dto.common.BaseResponse;
import org.openmore.platform.framework.MyThreadLocalConfig;
import org.openmore.platform.wechatOpen.MyWxOpenService;
import org.openmore.platform.wechatOpen.MyWxOpenServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE;

/**
 * 微信开放品台接口
 * 参考：
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 */
@Api(value = "/WechatOpen", tags = "WechatOpen", description = "开放平台-三方平台-网页登录相关接口")
@RequestMapping(value = "/api/wechatOpen", produces = {APPLICATION_JSON_UTF8_VALUE})
@RestController
public class WxOpenController extends BaseController{
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MyWxOpenService myWxOpenService;

    @TokenAuthCheck
    @ApiOperation(value = "获取跳转链接", response = String.class)
    @ApiResponses(value = {@ApiResponse(code = 4000, message = "请求失败：原因", response = String.class)})
    @RequestMapping(method = RequestMethod.GET, value = "/{tenantId}/gotoAuthUrl")
    public BaseResponse gotoPreAuthUrlShow(@PathVariable @RequestParam(name = "应用ID") String tenantId){
        logger.debug("==>tenant:"+ MyThreadLocalConfig.getTenant());
        return BaseResponse.buildSuccessResponse("<a href='goto_auth_url'>go</a>");
    }

    @ApiOperation(value = "跳转授权", response = String.class)
    @ApiResponses(value = {@ApiResponse(code = 4000, message = "请求失败：原因", response = String.class)})
    @RequestMapping(method = RequestMethod.GET, value = "/{tenantId}/authGet", produces = "text/plain;charset=utf-8")
    public void gotoPreAuthUrl(HttpServletRequest request, HttpServletResponse response,
                               @PathVariable @RequestParam(name = "应用ID") String tenantId){
        String host = request.getHeader("host");
        try {
            String url = myWxOpenService.getPreAuthUrl(request, tenantId);
            // 添加来源，解决302跳转来源丢失的问题
            response.addHeader("Referer", "http://"+host);
            response.sendRedirect(url);
        } catch (IOException e) {
            logger.error("gotoPreAuthUrl", e);
            throw new OpenmoreException(400, "接口出错,IO异常");
        }
    }
    @ApiOperation(value = "跳转获取授权信息", response = String.class)
    @ApiResponses(value = {@ApiResponse(code = 4000, message = "请求失败：原因", response = String.class)})
    @RequestMapping(method = RequestMethod.GET, value = "/{tenantId}/jump/{authorizationCode}")
    public BaseResponse jump(@PathVariable @RequestParam(name = "应用ID") String tenantId,
                             @PathVariable("authorizationCode") @ApiParam("authorizationCode")String authorizationCode){
        return BaseResponse.buildSuccessResponse(myWxOpenService.jump(tenantId, authorizationCode));
    }
    @ApiOperation(value = "获取授权方账号基本信息", response = String.class)
    @ApiResponses(value = {@ApiResponse(code = 4000, message = "请求失败：原因", response = String.class)})
    @RequestMapping(method = RequestMethod.GET, value = "/{tenantId}/authorInfo")
    public BaseResponse getAuthorizerInfo(@PathVariable @RequestParam(name = "应用ID") String tenantId){
        return BaseResponse.buildSuccessResponse(myWxOpenService.getAuthorizerInfo(tenantId));
    }

    /**
     * 接受微信服务器认证消息
     */
    @ApiOperation(value = "接收ticket", response = String.class)
    @ApiResponses(value = {@ApiResponse(code = 4000, message = "请求失败：原因", response = String.class)})
    @RequestMapping(value = "/{tenantId}/receiveTicket")
    public Object receiveTick(@PathVariable @ApiParam(name = "应用ID") String tenantId,
                              @RequestBody(required = false) @ApiParam String requestBody,
                              @RequestParam("timestamp") @ApiParam String timestamp,
                              @RequestParam("nonce") @ApiParam String nonce,
                              @RequestParam("signature") @ApiParam String signature,
                              @RequestParam(name = "encType", required = false) @ApiParam String encType,
                              @RequestParam(name = "msgSignature", required = false) @ApiParam String msgSignature) {
        return myWxOpenService.receiveTick(tenantId, requestBody, timestamp, nonce, signature, encType, msgSignature);
    }
    /**
     * 接受微信服务器认证消息
     */
    @ApiOperation(value = "回调消息", response = String.class)
    @ApiResponses(value = {@ApiResponse(code = 4000, message = "请求失败：原因", response = String.class)})
    @RequestMapping(value = "/{{tenantId}}/callback")
    public Object callback(@PathVariable @ApiParam(name = "应用ID") String tenantId,
                           @RequestBody(required = false) String requestBody,
                           @RequestParam("signature") String signature,
                           @RequestParam("timestamp") String timestamp,
                           @RequestParam("nonce") String nonce,
                           @RequestParam("openid") String openid,
                           @RequestParam("encrypt_type") String encType,
                           @RequestParam("msg_signature") String msgSignature){
        return myWxOpenService.callback(tenantId, requestBody, signature, timestamp, nonce, openid, encType, msgSignature);
    }
}